package v1

import (
	"RoccBlog/global"
	"RoccBlog/model"
	"RoccBlog/repository"
	"RoccBlog/util"
	"gorm.io/gorm"
)

type RoleRepository struct {
	repository.BaseRepository
}

func (r *RoleRepository) Create(data model.Role) error {
	return global.DB.Create(&data).Error
}

// UpdatePermission 修改角色权限
func (r *RoleRepository) UpdatePermission(data model.Role) error {
	return global.DB.Model(&data).Association("Permissions").Replace(data.Permissions)
}

// UpdateRouter 修改角色路由
func (r *RoleRepository) UpdateRouter(data model.Role) error {
	return global.DB.Model(&data).Association("Routers").Replace(data.Routers)
}

func (r *RoleRepository) Delete(id int) error {
	return global.DB.Delete(&model.Role{}, id).Error
}

func (r *RoleRepository) Update(data model.Role) error {
	return global.DB.Model(&data).Updates(&data).Error
}

func (r *RoleRepository) Select(pageNum, pageSize int) (any, error) {
	var (
		list  []model.Role
		count int64
		err   error
	)
	db := global.DB.Model(&model.Role{})

	err = db.Count(&count).Error
	if err != nil {
		return nil, err
	}

	err = db.Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&list).Error
	return util.ToPageInfo(count, pageSize, pageNum, list), err

}

func (r *RoleRepository) SelectById(id int) (model.Role, error) {
	var role model.Role
	err := global.DB.Preload("Permissions").Preload("Routers", func(db *gorm.DB) *gorm.DB {
		// 对路由进行排序
		return db.Order("weight asc")
	}).Take(&role, id).Error
	return role, err
}
